﻿#region

using System;
using System.IO;
using System.Net;
using System.Xml;

#endregion

namespace HudsonMonitor
{
    public class NetUtils
    {
        public XmlDocument GetHudsonXml(string url)
        {
            XmlDocument xml = new XmlDocument();
            StreamReader reader = null;
            Stream webStream = null;
            WebResponse response;
            string pageContent = "";

            try
            {
                // Open a connection
                HttpWebRequest webRequestObject = (HttpWebRequest) WebRequest.Create(url);

                // You can also specify additional header values like 
                // the user agent or the referer:
                webRequestObject.UserAgent = "Hudson monitor";
                webRequestObject.Referer = "http://www.capgemini.dk";

                // Request response:
                response = webRequestObject.GetResponse();

                // Open data stream:
                webStream = response.GetResponseStream();

                // Create reader object:
                if (webStream != null) reader = new StreamReader(webStream);

                // Read the entire stream content:
                if (reader != null) pageContent = reader.ReadToEnd();

                xml.LoadXml(pageContent);
            }
            catch (Exception)
            {
                MainWindow.GetReference().SetStatusbarMessage("Error while connecting to hudson on " + url);
            }
            finally
            {
                // Cleanup by closing stream (indirectly reader + response)
                if (webStream != null) webStream.Close();
            }

            return xml;
        }
    }
}